package db

import (
	"fmt"
	"hobby-mate/entity"
	"hobby-mate/middleware/globalLogger"
)

// doAutoMigrate 建立数据库表
func doAutoMigrate() error {
	fmt.Println("开始建表")
	err := Db.AutoMigrate(
		&entity.Account{},
		&entity.AccountRelationship{},
		&entity.Activity{},
		&entity.ActivityCheckin{},
		&entity.BannerInfo{},
		&entity.ChatRoom{},
		&entity.Post{},
		&entity.SessionInformationHistory{},
	)
	if err != nil {
		globalLogger.Error(map[string]interface{}{
			"auto migrate failed": err.Error(),
		})
		fmt.Print("auto migrate failed")
		return err
	}
	fmt.Println("建表完成")
	return nil
}

// CheckAndCreateDb 以基础Account表为准，检查是否存在数据库检查本地有没有db_hobby_mate数据库，没有则执行migration
func CheckAndCreateDb() error {
	var accountTableNames string
	err = Db.Raw("SHOW TABLES LIKE 't_account'").Scan(&accountTableNames).Error
	if err != nil {
		panic(err)
	}
	if len(accountTableNames) > 0 {
		return nil
	} else {
		return doAutoMigrate()
	}

}
